package controllers

import (
	"strings"

	"beego_blog/cache"

	"github.com/astaxie/beego"
)

type JsonMsg struct {
	Code int
	Msg  string
	Data interface{}
}

type baseController struct {
	beego.Controller
}

func (p *baseController) Prepare() {
	if p.Ctx.Request.Method == "POST" {
		// 如果是登录请求的话，放行
		uri := p.Ctx.Input.URI()
		if uri == "/user/login" {
			return
		}

		// 身份校验
		username := p.Ctx.Input.Cookie("username")
		auth := p.Ctx.Input.Cookie("Authorization")
		v, ok := cache.Authcache.Get(auth)
		if !ok || username != v {
			p.ErrorJson(403, "无权限")
			p.StopRun()
			return
		}

	}
}

func (p *baseController) History(msg string, url string) {
	if url == "" {
		p.Ctx.WriteString("<script>alert('" + msg + "');window.history.go(-1);</script>")
		p.StopRun()
	} else {
		p.Redirect(url, 302)
	}
}

// 成功时返回JSON
func (p *baseController) SuccessJson(data interface{}) {
	jsonMsg := JsonMsg{200, "success", data}
	p.Data["json"] = jsonMsg
	p.ServeJSON()
}

// 失败时返回JSON
func (p *baseController) ErrorJson(code int, data interface{}) {
	jsonMsg := JsonMsg{code, "failed", data}
	p.Data["json"] = jsonMsg
	p.ServeJSON()
}

// 获取用户IP地址
func (p *baseController) getClientIp() string {
	s := strings.Split(p.Ctx.Request.RemoteAddr, ":")
	return s[0]
}
